<?php

namespace app\controller\wmapi\order;

use app\controller\wmapi\approvalsetting\ApproveSettingController;
use app\controller\wmapi\message\MessageNotifyController;
use app\controller\wmapi\partner\MemberController;
use App\Library\Y;
use app\model\WaAccountingInformationRelevance;
use app\model\WaAdmins;
use app\model\WaApproveSetting;
use app\model\WaDepartment;
use app\model\WaMembers;
use app\model\WaMonthlySettlement;
use app\model\WaOrders;
use app\model\WaOrdersContract;
use app\model\WaOrdersOperateLog;
use app\model\WaOrdersOperateLogVin;
use app\model\WaOrdersPurchase;
use app\model\WaOrdersPurchaseRelevance;
use app\model\WaOrdersQuotation;
use app\model\WaOrdersQuotationAmountDetail;
use app\model\WaOrdersQuotationRelevance;
use app\model\WaOrdersRelevance;
use app\controller\wmapi\IndexController;
use app\controller\wmapi\PublicCommentController;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaProducts;
use app\model\WaPurchasedVehicles;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaRegistrationCompany;
use app\model\WaSalesOrdersExamineApprove;
use app\model\WaSalesOrdersExamineApproveFlow;
use app\model\WaSupplier;
use app\model\WaSupplierRegistrationFee;
use app\model\WaTransferExportCompany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;
use app\model\WaOrdersSalesAmountDetail;
use app\model\WaAccountingInformation;



class OrderController extends Validate
{

    /**
     * 创建销售订单
     * @param Request $request
     * @return Response
     * 获取报价单信息
     * 判断是否已创建
     * 报价单状态修改
     * 报价单状态日志添加
     * 主订单数据创建
     * 关联产品订单数据创建
     * 销售订单日志添加
     *
     */
    public function createOrder(Request $request)
    {
        PublicCommentController::销售订单状态;
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        if (!array_key_exists('user_id', $param)) {
            return IndexController::errored('', '缺少用户id');
        }

        // 获取报价单信息
        if ($param['quotation_order_sn']) {
            $quotation_order = WaOrdersQuotation::find(['quotation_order_sn' => $param['quotation_order_sn']]);
            if ($quotation_order) {
                $quotation_order = json_decode($quotation_order);

//                if ($quotation_order->status != 2) {
//                    return IndexController::errored('', '只有待下载状态才能创建销售订单');
//                }
                // 判断是够已经创建过销售当 且在订单未结束
//                $sale_order = WaOrders::find(['quotation_order_sn' => $param['quotation_order_sn']]);
//                $sale_order = json_decode($sale_order);
//                if ($sale_order) {
//                    //销售订单状态
//                   PublicCommentController::销售订单状态;
//                    if (!in_array($sale_order->status, [9, 10, 11])) {
//                        return IndexController::errored('', '销售订单已存在，无需重复创建');
//                    } elseif ($sale_order->status == 9) {
//                        return IndexController::errored('', '销售订单已完成，无需重复创建');
//                    }
//                }
            } else {
                return IndexController::errored('', '报价单编号获取数据为空');
            }
        } else {
            return IndexController::errored('', '报价单编号为空无法创建');
        }
        // 获取客户信息
        $where = [];
        $where [] = ['id', '=', $param['user_id']];
        $member = WaMembers::find($where);
        $member = json_decode($member);
        if (!$member) {
            return IndexController::errored('', '获取客户信息失败');
        }
        PublicCommentController::销售订单状态;
        // 必传参数
        // 销售订单编号
        $sn = IndexController::generateOrderSn();
        // 今天开始时间
        $todayStart = strtotime("today");
        // 今天结束时间
        $todayEnd = strtotime("tomorrow") - 1;
        //获取当前用户今日的订单数量
        $admin_order_count_todady = WaOrders::ordersCountByAdmin($todayStart,$todayEnd,$adminId);
        $admin_order_count_todady = $admin_order_count_todady + 1;
        if ($admin_order_count_todady < 10){
            $admin_order_count_todady = str_pad($admin_order_count_todady, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
        }
        if (!$adminId->nickname_abbreviation){
            $adminId->nickname_abbreviation = 'TS'.$adminId->id;
        }

        // 获取出口公司信息
        $where_ext_company = [];
        $where_ext_company [] = ['id', '=', $param['transfer_export_company_id']];
        $ext_company_data = WaTransferExportCompany::find($where_ext_company);
        $ext_company_data = json_decode($ext_company_data);
        if (!$ext_company_data) {
            return IndexController::errored('', '获取出口信息失败');
        }




        // 获取今日结束时间
        $order_sn = $ext_company_data->alias_name.'SAL' . $sn . $adminId->nickname_abbreviation.$admin_order_count_todady; // 父订单编号 销售订单编号
        $order_data = [
            'order_sn' => $order_sn,
            'user_id' => $param['user_id'], // 用户id
            'user_name' => $member->name, // 用户名称
            'country' => $member->country,
            'address' => $member->address,
            'phone' => $member->phone,
            'email' => $member->email,
            'user_type' => $member->type, // 1个人 2 企业
            'passport_number' => $member->passport_number, // 护照号码
            'business_license_number' => $member->business_license_number, // 营业执照号


            'orders_type' => $quotation_order->orders_type, // 订单类型
            'admin_id' => $adminId->id, // 管理员
            'admin_name' => $adminId->nickname, // 管理员名称
            'quotation_order_sn' => $param['quotation_order_sn'], // 报价单编号
            'pol' => $quotation_order->pol, // POL装港
            'pod' => $quotation_order->pod, // POD卸港
            'pol_en' => $quotation_order->pol_en, // POL装港
            'pod_en' => $quotation_order->pod_en, // POD卸港
            'condition' => $quotation_order->condition, // 交货条件
            'cnh' => $quotation_order->cnh, // 美元汇率
            'status' => 0,
            'created_at' => date('y-m-d h:m:s', time()), // 创建时间
            'currency' => $quotation_order->currency, // 货币类型   1人民币 2 美元 3 欧元
            'shipment' => $quotation_order->shipment, // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)
            'user_linkman' => $member->linkman,
            'total_premium_price' => $quotation_order->total_premium_price,
            'total_amount' => $quotation_order->total_amount,
            'transfer_export_company_id' => $ext_company_data->id, // 出口公司id
            'transfer_export_credit_code' => $ext_company_data->credit_code, // 出口公司-组织机构信用代码
            'transfer_export_company_name' => $ext_company_data->name, // 出口公司名字
            'transfer_export_company_province' => $ext_company_data->province, //出口公司-省份
            'transfer_export_company_city' => $ext_company_data->city, //出口公司-市
            'transfer_export_company_alias_name' => $ext_company_data->alias_name, //出口公司别名代号

        ];


        $specs = WaOrdersQuotationRelevance::all(['order_sn_parent' => $quotation_order->quotation_order_sn]); // 查询报价单的所有子订单车型
        if ($specs) {
            $specs = json_decode($specs);
        } else {
            return IndexController::errored('', '该笔报价单未选择车型，信息有误');
        }
        \support\Db::beginTransaction();
        try {
            if ($specs) {
                $orders_id = WaOrders::created($order_data); // 创建订单
                if (!$order_sn) {
                    return IndexController::errored('', '创建订单失败');
                }
                $total_price = 0; // 总价
                foreach ($specs as $k) {
                    $order_sn_child = 'WMXDZ' . IndexController::generateOrderSnOther(); // 子订单编号

                    $order_detail_data = [
                        'order_sn_parent' => $order_sn, // 父订单编号
                        'order_sn_child' => $order_sn_child, // 子订单编号

                        'product_no' => $k->product_no, // 关联产品编号
                        'product_type' => $k->product_type, // 产品类型
//                        'car_type' => $k->car_type, // 汽车类型
                        'brands_name' => $k->brands_name, // 品牌
                        'series_name' => $k->series_name, // 车系
                        'model' => $k->model, // 车型名称

                        'is_nev' => $k->is_nev, // 是否新能源 1 是 2 传统能源
                        'market_time' => $k->market_time, // 上市日期
                        'vehicle_status' => $k->vehicle_status ? round($k->vehicle_status, 2) : 0, // 车辆状况(是否是新车)  1 新车 2 二手车


//                        'fas_base_price' => $k->fas_base_price ? round($k->fas_base_price, 2) : 0, //  底价
                        'premium_price' => $k->premium_price ? round($k->premium_price, 2) : 0, //  溢价
                        'final_offer_price' => $k->final_offer_price ? round($k->final_offer_price, 2) : 0, //  最终报价


                        'guide_price' => $k->guide_price, // 指导价
                        'option_package' => json_encode($k->option_package), // 选装包 ["option_package"]=>
//                        'option_package_price' => $k->option_package_price, // 选装包价格
                        'traffic_compulsory_insurance' => $k->traffic_compulsory_insurance, // 交强险
//                        'purchase_tax' => $k->purchase_tax, // 购置税

//                        'registration_province' => $k->registration_province, //  上牌省份
//                        'registration_city' => $k->registration_city, // 上牌市
//                        'registration_area' => $k->registration_area, // 上牌区
//                        'transfer_export_province' => $k->transfer_export_province, // 转移待出口省份
//                        'transfer_export_city' => $k->transfer_export_city, // 转移待出口上牌市
//                        'transfer_export_area' => $k->transfer_export_area, // 转移待出口上牌区
//
//                        'registration_id' => $k->registration_id ? intval($k->registration_id) : 0, // 上牌服务商id
//                        'transfer_export_id' => $k->transfer_export_id ? intval($k->transfer_export_id) : 0, // 转移待出口服务商id

//                        'port_charges' => $k->port_charges ? round($k->port_charges, 2) : 0, // 集港运费
                        'port_departure_charges' => $k->port_departure_charges ? round($k->port_departure_charges, 2) : 0, // 起运港港杂费
                        'premium_charges' => $k->premium_charges ? round($k->premium_charges, 2) : 0, // 国际运输保险费
                        'international_freight' => $k->international_freight ? round($k->international_freight, 2) : 0, // 国际运费
//                        'kilometres' => $k->kilometres ? round($k->kilometres, 2) : 0, // 公里数
                        'count' => $k->count ? intval($k->count) : 0, // 数量
                        'to_be_purchase_count' => $k->count ? intval($k->count) : 0, // 待采购数量
                        'total_price' => $k->total_price ? round($k->total_price, 2) : 0, // 总价
                        'created_at' => date('y-m-d h:m:s', time()), // 创建时间

//                        'other_price' => json_encode($k->other_price), // 其它费用

//                        "urban_trailer_fee" => $k['urban_trailer_fee'] ? round($k['urban_trailer_fee'], 2) : 0, // 城区拖车费
//                        "domestic_storage_fees" => $k['domestic_storage_fees'] ? round($k['domestic_storage_fees'], 2) : 0, // 国内仓储费
//                        "car_wash_beauty_fee" => $k['car_wash_beauty_fee'] ? round($k['car_wash_beauty_fee'], 2) : 0, // 洗车美容费
//                        "used_car_check_fee" => $k['used_car_check_fee'] ? round($k['used_car_check_fee'], 2) : 0, // 二手车检测费/第三方检测费
//                        "port_price" => $k['port_price'] ? round($k['port_price'], 2) : 0, // 集港物流费
//                        "export_testing_fee" => $k['export_testing_fee'] ? round($k['export_testing_fee'], 2) : 0, // 出口检测费

                        'sub_brand_name' => $k->sub_brand_name, // 厂商
                        'purchase_quotation' => $k->purchase_quotation ? round($k->purchase_quotation, 2) : 0, // 行情报价
                        'purchase_price' => $k->purchase_price ? round($k->purchase_price, 2) : 0, // 二手车采购价格
                        'VAT_invoice_price' => $k->VAT_invoice_price ? round($k->VAT_invoice_price, 2) : 0, // 增值税发票金额
                        'retail_concessions' => $k->retail_concessions ? round($k->retail_concessions, 2) : 0, // 零售优惠
                        'other_rebates' => $k->other_rebates ? round($k->other_rebates, 2) : 0, // 采购返利
                        'registration_fee' => $k->registration_fee ? round($k->registration_fee, 2) : 0, //  上牌费用
                        'used_car_fee' => $k->used_car_fee ? round($k->used_car_fee, 2) : 0, //  二手车过户费用
                        'transfer_export_fee' => $k->transfer_export_fee ? round($k->transfer_export_fee, 2) : 0, // 转移待出口费用
                        'price_options' => json_encode($k->price_options), // 费用选项
                        'seat_count' => $k->seat_count, // 座位数
                        'car_year' => $k->car_year, //  车辆年款
                        'jb' => $k->jb, // 级别
                        'series_type' => $k->series_type, // 车身类型
                        'driver_form' => $k->driver_form, // 驱动方式
                        'length' => $k->length, // 长
                        'width' => $k->width, // 宽
                        'height' => $k->height, // 高
                        'curb_weight' => $k->curb_weight, // 设计重量
                        'resource_service_fee' => $k->resource_service_fee, // 资源服务费
                        'color_interior' => $k->color_interior, // 内饰颜色
                        'color_exterior' => $k->color_exterior, // 外观颜色
                        'model_en' => $k->model_en, //
                        'series_name_en' => $k->series_name_en, // 车系
                        'brands_name_en' => $k->brands_name_en, // 品牌
                        'fuel_form_en' => $k->fuel_form_en, // 能源类型
                        'color_interior_en' => $k->color_interior_en, // 内饰颜色
                        'color_exterior_en' => $k->color_exterior_en, // 外观颜色
                        'sub_brand_name_en' => $k->sub_brand_name_en, // 厂商
                        'is_drawback' => $k->is_drawback, // 是否退税
                        'is_CLIVTA' => $k->is_CLIVTA, // 是否交强险  文森说的 要大些

                        'other_price_total' => $k->other_price_total ? round($k->other_price_total, 2) : 0, // 其它费用总额
                    ];

                        if ($k->other_price){
                            $order_detail_data['other_price'] = json_encode($k->other_price); // 其它费用
                        }


                        if ($k->invoice_price){
                            $order_detail_data['invoice_price'] = $k->invoice_price; // 机动车专用发票价
                        }

                    $total_price = $total_price + $order_detail_data['total_price'];
                    $order_detail_data ['orders_id'] = $orders_id;

                    $order_detail_id = WaOrdersRelevance::created($order_detail_data); // 创建订单详情
                    if (!$order_detail_id) {
                        return IndexController::errored($order_detail_id, '创建订单详情失败');
                    }
                }


            } else {
                return IndexController::errored($specs, '创建失败，车型数据为空');
            }

            // 统计 报价单 生成订单次数
            $quotation_order_count = $quotation_order->generate_order_count + 1;
            $quotation_order_condition = [];
            $quotation_order_condition [] = ['quotation_order_sn','=', $param['quotation_order_sn']];
            $quotation_order_data = [];
            if ($quotation_order_count && intval($quotation_order_count) != 0 ){
                $quotation_order_data ['generate_order_count'] = intval($quotation_order_count);
                $quotation_order_data ['updated_at'] = dateTime();
                $quotation_status = WaOrdersQuotation::updated($quotation_order_data, $quotation_order_condition);
                if (!$quotation_status) {
                    return IndexController::errored('', '报价单生成订单次数修改失败');
                }
            }

            //添加销售订单账单明细
            $quotation_amount_condition = [];
            $quotation_amount_condition [] = ['quotation_order_sn', '=', $param['quotation_order_sn']];
            $bill_details = WaOrdersQuotationAmountDetail::all($quotation_amount_condition);
            if ($bill_details) {
                $bill_details = json_decode($bill_details);
                if ($bill_details) {
                    foreach ($bill_details as $kd) {
                        $bill_details_data = [
                            'sales_order_sn' => $order_sn, //
                            'total_amount' => $kd->total_amount, //
                            'price_name' => $kd->price_name, //
                            'admin_id' => $adminId->id, //
                            'admin_name' => $adminId->nickname, //
                            'created_at' => dateTime(), //
                        ];

                        $bill_details_id = WaOrdersSalesAmountDetail::created($bill_details_data); // 创建订单详情
                        if (!$bill_details_id) {
                            return IndexController::errored($bill_details_id, '添加销售订单账单明细失败');
                        }
                    }
                } else {
                    return IndexController::errored($specs, '采购费用，参数值为空');
                }

            }

            \support\Db::commit();
            $res_data = [
                'order_sn' => $order_sn,
            ];

            return IndexController::successed( json_encode($res_data), '订单创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('createOrder', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '订单创建失败');
        }

    }

    /**
     * 更新订单
     * @param Request $request
     * @return Response
     * 查看订单状态
     * 如果出现 数据问题 先排查订单编号是否正确
     * 更新 主订单数据 和 子订单数据 并添加操作日志
     * 销售订单：【作废、审批驳回】提供重新编辑操作。
     */
    public function updateOrder(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));

        if ($param['transfer_export_company_id']) {
            $transfer_export_condition = [];
            $transfer_export_condition [] = ['id', '=', $param['transfer_export_company_id']];
            $transfer_export_company = WaRegistrationCompany::find($transfer_export_condition);
            if (!$transfer_export_company) {
                return IndexController::errored('', '出口公司信息为空');
            }
        } else {
            return IndexController::errored('', '出口公司id为必填');
        }



        PublicCommentController::销售订单状态;
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }

        $result = [
            'order_sn' => $param['order_sn'], // Y
            'admin_id' => $adminId->id, // Y
            'user_id' => $param['user_id'], // Y
            'phone' => $param['phone'],
            'email' => $param['email'],
            'pol' => $param['pol'],
            'pod' => $param['pod'],
            'pol_en' => $param['pol_en'],
            'pod_en' => $param['pod_en'],
            'condition' => $param['condition'],
            'specs_can' => $param['specs_can'],
        ];

        $specs = $result['specs_can'];
        $condition = ['id' => intval($param['user_id'])];
        // 获取客户信息
        $where = [];
        $where [] = ['id', '=', $param['user_id']];
        $member = WaMembers::find($where);
        $member = json_decode($member);
        if (!$member) {
            return IndexController::errored('', '获取客户信息失败');
        }
        PublicCommentController::销售订单状态;



        // 父订单更新
        $order_data = [
            'user_id' => $param['user_id'], // 用户id
            'user_name' => $param['user_name'], // 用户名称
            'country' => $param['country'], //
            'address' => $param['address'], //
            'phone' => $param['phone'],
            'email' => $param['email'],
            'user_type' => $member->type,
            'passport_number' => $member->passport_number,
            'business_license_number' => $member->business_license_number,

            'orders_type' => $param['orders_type'], // 订单类型
            'pol' => $param['pol'],
            'pod' => $param['pod'],
            'condition' => $param['condition'],
            'cnh' => $param['cnh'], // 美元汇率
            'currency' => $param['currency'], // 币种 1 人民币 2 美元 3 欧元

            'deeposit_ratio' => $param['deeposit_ratio'],// 定金比例
            'deeposit_amount' => $param['deeposit_amount'],// 定金金额
            'consignee_name' => $param['consignee_name'],// 收货人名称

            'consignee_document_type' => $param['consignee_document_type'],// 收货人证件类型： 护照 营业执照号
            'consignee_document_num' => $param['consignee_document_num'],// 收货人证件号码
            'consignee_document_phone' => $param['consignee_document_phone'],// 收货人电话
            'consignee_document_email' => $param['consignee_document_email'],// 收货人邮箱
            'consignee_document_address' => $param['consignee_document_address'],// 收货人地址
            'notifier_name' => $param['notifier_name'],// 通知人姓名
            'notifier_phone' => $param['notifier_phone'],// 通知人电话
            'notifier_email' => $param['notifier_email'],// 通知人邮箱
            'notifier_address' => $param['notifier_address'],// 收货人地址
            'shipment' => $param['shipment'], // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)
            'user_linkman' => $param['user_linkman'], // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)

            'transfer_export_company_id' => $param['transfer_export_company_id'], // 出口公司id
            'transfer_export_credit_code' => $param['transfer_export_credit_code'], // 出口公司-组织机构信用代码
            'transfer_export_company_name' => $param['transfer_export_company_name'], // 出口公司名字
            'transfer_export_company_province' => $param['transfer_export_company_province'], //出口公司-省份
            'transfer_export_company_city' => $param['transfer_export_company_city'], //出口公司-市
            'transfer_export_company_alias_name' => $param['transfer_export_company_alias_name'], //出口公司别名代号
            'remark' => $param['remark'], //备注
            'status' => 0,
            'updated_at' => dateTime(), // 创建时间
        ];
        // 判断总毛利(溢价)
        if (array_key_exists('total_premium_price',$param)){
            $order_data['total_premium_price'] = $param['total_premium_price'];
        }

        if (array_key_exists('total_amount',$param)){
            $order_data['total_amount'] = $param['total_amount'];
        }

        if (array_key_exists('transfer_export_company_account',$param)){
            if ($param['transfer_export_company_account']){
                $order_data['transfer_export_company_account'] = json_encode($param['transfer_export_company_account']);
            }
        }
        if (array_key_exists('consignee_link_name',$param)){
            if ($param['consignee_link_name']){
                $order_data['consignee_link_name'] = $param['consignee_link_name'];// 收货联系人姓名
            }
        }


        if (array_key_exists('pol_en',$param)){
            if ($param['pol_en']){
                $order_data['pol_en'] = $param['pol_en'];// POL装港en
            }
        }

        if (array_key_exists('pod_en',$param)){
            if ($param['pod_en']){
                $order_data['pod_en'] = $param['pod_en'];// POD卸港en
            }
        }

//        $order_data['source_type'] = $param['source_type'];


        \support\Db::beginTransaction();
        try {
            if ($specs) {
                $ordersUp = WaOrders::updated($order_data, ['order_sn' => $param['order_sn']]); // 更新报价单
                if (!$ordersUp) {
                    return IndexController::errored('', '销售订单更新失败');
                }
                //删除旧的子订单数据
                $quotationDel = WaOrdersRelevance::delete(['order_sn_parent' => $param['order_sn']]); // 删除之前创建的 添加新的数据

                // 创建新的子订单数据
                foreach ($specs as $k) {

                    $order_sn_child = 'WMXDZ' . IndexController::generateOrderSnOther(); // 子订单编号

                    $order_detail_data = [
                        'order_sn_parent' => $param['order_sn'], // 父订单编号
                        'order_sn_child' => $order_sn_child, // 子订单编号
                        'brands_name' => $k['brands_name'], // 品牌
                        'series_name' => $k['series_name'], // 车系
                        'model' => $k['model'], // 车型名称
                        'is_nev' => $k['is_nev'], // 是否新能源 1 是 2 传统能源
                        'market_time' => $k['market_time'], // 上市日期
                        'vehicle_status' => $k['vehicle_status'] ? round($k['vehicle_status'], 2) : 0, // 车辆状况(是否是新车)  1 新车 2 二手车
                        'guide_price' => $k['guide_price'] ? round($k['guide_price'], 2) : 0, // 指导价
                        'option_package' => json_encode($k['option_package']), // 选装包
                        'traffic_compulsory_insurance' => $k['traffic_compulsory_insurance'] ? round($k['traffic_compulsory_insurance'], 2) : 0, // 交强险
                        'premium_price' => $k['premium_price'] ? round($k['premium_price'], 2) : 0, //  溢价
                        'final_offer_price' => $k['final_offer_price'] ? round($k['final_offer_price'], 2) : 0, //  最终报价 / 报价单价
                        'port_departure_charges' => $k['port_departure_charges'] ? round($k['port_departure_charges'], 2) : 0, // 起运港港杂费
                        'international_freight' => $k['international_freight'] ? round($k['international_freight'], 2) : 0, // 国际运费
                        'count' => $k['count'] ? round($k['count'], 2) : 0, // 数量
                        'to_be_purchase_count' => $k['count'] ? round($k['count'], 2) : 0, // 待采购数量
                        'sub_brand_name' => $k['sub_brand_name'], // 厂商
                        'purchase_quotation' => $k['purchase_quotation'] ? round($k['purchase_quotation'], 2) : 0, // 行情报价
                        'purchase_price' => $k['purchase_price'] ? round($k['purchase_price'], 2) : 0, // 二手车采购价格
                        'VAT_invoice_price' => $k['VAT_invoice_price'] ? round($k['VAT_invoice_price'], 2) : 0, // 增值税发票金额
                        'retail_concessions' => $k['retail_concessions'] ? round($k['retail_concessions'], 2) : 0, // 零售优惠
                        'other_rebates' => $k['other_rebates'] ? round($k['other_rebates'], 2) : 0, // 采购返利
                        'registration_fee' => $k['registration_fee'] ? round($k['registration_fee'], 2) : 0, //  上牌费用
                        'used_car_fee' => $k['used_car_fee'] ? round($k['used_car_fee'], 2) : 0, //  二手车过户费用
                        'transfer_export_fee' => $k['transfer_export_fee'] ? round($k['transfer_export_fee'], 2) : 0, // 转移待出口费用
                        'total_price' => $k['total_price'] ? round($k['total_price'], 2) : 0,
                        'premium_charges' => $k['premium_charges'] ? round($k['premium_charges'], 2) : 0,// 国际运输保险费
                        'price_options' => json_encode($k['price_options']), // 费用选项
                        'seat_count' => $k['seat_count'], // 座位数
                        'car_year' => $k['car_year'], //  车辆年款
                        'jb' => $k['jb'], // 级别
                        'series_type' => $k['series_type'], // 车身类型
                        'driver_form' => $k['driver_form'], // 驱动方式
                        'length' => $k['length'], // 长
                        'width' => $k['width'], // 宽
                        'height' => $k['height'], // 高
                        'curb_weight' => $k['curb_weight'], // 设计重量
                        'resource_service_fee' => $k['resource_service_fee'], // 资源服务费
//                        'created_at' => date('y-m-d h:m:s', time()), // 创建时间
                        'updated_at' => date('y-m-d h:m:s', time()), // 创建时间

//                        'car_type' => $k['car_type'], // 汽车类型
//                        'fas_base_price' => $k['fas_base_price'] ? round($k['fas_base_price'], 2) : 0, //  底价
//                        'option_package_price' => $k['option_package_price'], // 选装包价格
//                        'purchase_tax' => $k['purchase_tax'], // 购置税
//                        'registration_province' => $k['registration_province'], //  上牌省份
//                        'registration_city' => $k['registration_city'], // 上牌市
//                        'registration_area' => $k['registration_area'], // 上牌区
//                        'transfer_export_province' => $k['transfer_export_province'], // 转移待出口省份
//                        'transfer_export_city' => $k['transfer_export_city'], // 转移待出口上牌市
//                        'transfer_export_area' => $k['transfer_export_area'], // 转移待出口上牌区
//                        'registration_id' => $k['registration_id'] ? intval($k['registration_id']) : 0, // 上牌服务商id
//                        'transfer_export_id' => $k['transfer_export_id'] ? intval($k['transfer_export_id']) : 0, // 转移待出口服务商id


//                        'port_charges' => $k['port_charges'] ? round($k['port_charges'], 2) : 0, // 集港运费
//                        'kilometres' => $k['kilometres'] ? round($k['kilometres'], 2) : 0, // 公里数
                        'total_price' => $k['total_price'] ? round($k['total_price'], 2) : 0, // 总价



                    ];

                    if (array_key_exists('color_interior',$k)){
                        $order_detail_data['color_interior'] = $k['color_interior']; // 内饰颜色
                    }
                    if (array_key_exists('color_exterior',$k)){
                        $order_detail_data['color_exterior'] = $k['color_exterior']; // 外观颜色
                    }

                    if (array_key_exists('model_en',$k)){
                        $order_detail_data['model_en'] = $k['model_en']; // 车型
                    }
                    if (array_key_exists('series_name_en',$k)){
                        $order_detail_data['series_name_en'] = $k['series_name_en']; // 车系
                    }
                    if (array_key_exists('brands_name_en',$k)){
                        $order_detail_data['brands_name_en'] = $k['brands_name_en']; // 品牌
                    }
                    if (array_key_exists('fuel_form_en',$k)){
                        $order_detail_data['fuel_form_en'] = $k['fuel_form_en']; // 能源类型
                    }
                    if (array_key_exists('color_interior_en',$k)){
                        $order_detail_data['color_interior_en'] = $k['color_interior_en']; // 内饰颜色
                    }
                    if (array_key_exists('color_exterior_en',$k)){
                        $order_detail_data['color_exterior_en'] = $k['color_exterior_en']; // 外观颜色
                    }
                    if (array_key_exists('sub_brand_name_en',$k)){
                        $order_detail_data['sub_brand_name_en'] = $k['sub_brand_name_en']; // 厂商
                    }

                    if (array_key_exists('is_drawback',$k)){
                        $order_detail_data['is_drawback'] = $k['is_drawback']; // 是否退税
                    }

                    if (array_key_exists('is_CLIVTA',$k)){
                        $order_detail_data['is_CLIVTA'] = $k['is_CLIVTA']; // 是否交强险  文森说的 要大些
                    }


                    if (array_key_exists('other_price',$k)){
                        if ($k['other_price']){
                            $order_detail_data['other_price'] = json_encode($k['other_price']); // 其它费用
                        }
                    }

                    if (array_key_exists('other_price_total',$k)){
                        if ($k['other_price_total']){
                            $order_detail_data['other_price_total'] = round($k['other_price_total'],2); // 其它费用总额
                        }
                    }

                    if (array_key_exists('invoice_price',$k)){
                        if ($k['invoice_price']){
                            $order_detail_data['invoice_price'] = $k['invoice_price']; // 机动车专用发票价
                        }
                    }


                    $order_detail_id = WaOrdersRelevance::created($order_detail_data); // 创建订单详情
                    if (!$order_detail_id) {
                        return IndexController::errored($order_detail_id, '创建子订单失败');
                    }
                }


            } else {
                return IndexController::errored($specs, '更新失败，参数值为空');
            }
            // 删除旧的账单明细
            $bill_del = WaOrdersSalesAmountDetail::deleted(['sales_order_sn' => $param['order_sn']]);

            //创建新的账单明细
            // 还没有获取采购订单的 账单明细

            $bill_details = $param['bill_details'];
            if ($bill_details) {
                foreach ($bill_details as $kd) {
                    $bill_details_data = [
                        'sales_order_sn' => $param['order_sn'], //
                        'total_amount' => $kd['total_amount'], //
                        'price_name' => $kd['price_name'], //
                        'admin_id' => $adminId->id, //
                        'admin_name' => $adminId->nickname, //
                        'created_at' => dateTime(), //
                    ];

                    $bill_details_id = WaOrdersSalesAmountDetail::created($bill_details_data); // 创建订单详情
                    if (!$bill_details_id) {
                        return IndexController::errored($bill_details_id, '添加采购订单账单明细失败');
                    }
                }
            } else {
                return IndexController::errored($specs, '采购费用，参数值为空');
            }

            \support\Db::commit();
            return IndexController::successed('', '订单更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('updateOrder', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '订单更新失败');
        }

    }

    /**
     * 提交审批
     * @param Request $request
     * @return Response
     */
    public function orderSubmitApprove(Request $request)
    {

        PublicCommentController::销售订单状态;
        // 订单状态 0 草稿
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
        $find = WaOrders::find(['order_sn' => $param['order_sn']]);
        $find = json_decode($find);


        if (!$find->pol || !$find->pod || !$find->cnh || !$find->currency || !$find->condition || !$find->shipment || !$find->deeposit_ratio
            || !$find->deeposit_amount || !$find->consignee_name || !$find->consignee_document_type || !$find->consignee_document_num
            || !$find->consignee_document_phone || !$find->consignee_document_email || !$find->transfer_export_company_id
            || !$find->notifier_name || !$find->notifier_phone || !$find->notifier_email || !$find->notifier_address
        ) {
            $data_bug = 'pol :' . $find->pol . '+++' . 'pod :' . $find->pod . '+++' . 'currency :' . $find->currency . '+++' . 'condition :' . $find->condition
                . '+++' . 'shipment :' . $find->shipment . '+++' . 'deeposit_ratio :' . $find->deeposit_ratio
                . '+++' . 'deeposit_amount :' . $find->deeposit_amount . '+++' . 'consignee_name :' . $find->consignee_name . '+++' . 'consignee_document_type :' . $find->consignee_document_type
                . '+++' . 'consignee_document_num :' . $find->consignee_document_num. '+++' . 'transfer_export_company_id :' . $find->transfer_export_company_id
                . '+++' . 'consignee_document_phone :' . $find->consignee_document_phone . '+++' . 'consignee_document_email :' . $find->consignee_document_email
                . $find->notifier_address . '+++' . 'notifier_name :' . $find->notifier_name . '+++' . 'notifier_phone :' . $find->notifier_phone
                . '+++' . 'notifier_email :' . $find->notifier_email . '+++' . 'notifier_address :' . $find->notifier_address;

            var_dump($data_bug);
            return IndexController::errored('OrderInformationNotComplete', '订单信息暂未完善，请前往编辑页面补充完善后重试');
        }


        // 根据销售订单编号获取订单信息
        $orders = WaOrders::find(['order_sn' => $param['order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取售订单信息失败');
        }

        $send_before = [];
        $send_after = [];
        if (array_key_exists('send_before',$param)){
            if ($param['send_before']){
                $send_before = $param['send_before'];
            }
        }

        if (array_key_exists('send_after',$param)){
            if ($param['send_after']){
                $send_after = $param['send_after'];
            }
        }
        // 获取当前用户对应部门所设置的审批流设置
//        $flow = ApproveSettingController::flowStting(2, $department_id);
        if (array_key_exists('flow',$param)){
            $flow = $param['flow'];
            $admin_ids = json_encode($flow[0]['approve_admin_id']);

//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息

        }else{
            if (array_key_exists('sort', $param)){
                if ($param['sort']){
                    $sort = $param['sort'];
                }else{
                    $sort = 0;
                }
            }else{
                $sort = 0;
            }
            $flow = ApproveSettingController::flowSttingBySort(2,$sort);// sort默认选第一个
            $send_after = ApproveSettingController::flowSttingBySendBefore(2,$sort);// 抄送人 - 前 默认选第一个
            $send_before = ApproveSettingController::flowSttingBySendAfter(2,$sort);// 抄送人 - 前 默认选第一个
            $admin_ids = json_encode($flow[0]->approve_admin_id);
        }





        if (!$flow) {
            return IndexController::errored('ErrorApproveSetting', '当前用户所在部门未设置审批流程，无法提交审批');
        }


//        $flow = $param['flow'];
        \support\Db::beginTransaction();
        try {
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $adminId->nickname . '通过该订单' . $param['order_sn'] . '核验修改状态为审批中(自动创建订单审批)',
                'remark' => '',
//                'reason' => $param['refuse_reason'],
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'created_at' => dateTime(),
            ];

            // 销售订单操作日志
            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }
            $status_up = OrderController::ordersStatusUp($param['order_sn'], $status);
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }

            $sale_no = 'SALEORDERNO' . IndexController::getRandomNum(6);
            $data = [
                'sale_no' => $sale_no, // 销售订单审批编号
                'sales_order_sn' => $param['order_sn'], // 销售订单编号
                'total_amount' => round($orders->total_amount, 2), // 订单金额
                'user_id' => $orders->user_id, // 用户编号id
                'user_name' => $orders->user_name, // 用户名字
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'initiator_admin_id' => $adminId->id, //
                'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                'created_at' => dateTime(), // 创建时间
                'approve_flow' => json_encode($flow), // 当前采购合同的审批流流程
            ];

            if ($send_before){
                $data['approve_flow_send_before'] = json_encode($send_after);
            }
            if ($send_after){
                $data['approve_flow_send_after'] = json_encode($send_before);
            }


            $add_PurchaseEa = WaSalesOrdersExamineApprove::create($data); // 创建的审批id
            if (!$add_PurchaseEa) {
                return IndexController::errored('', '创建销售订单审批驳回');
            }
            // 同步审批id 到主订单列表
            $up_orders_status = WaOrders::updated(['approve_id' => $add_PurchaseEa, 'sale_no' => $sale_no, 'status' => 2, 'updated_at' => dateTime()],
                ['order_sn' => $param['order_sn']]);
            if (!$up_orders_status) {
                return IndexController::errored('', '同步审批id 到主订单列表失败');
            }

            $approve_log_data = [
                'sale_no' => $sale_no, // 销售单审批编号
                'check_id' => $add_PurchaseEa, // 审核id
//                'check_on' => $sales_approve->sale_no, // 审核编号
                'admin_ids' => $admin_ids, //  （撤回的时候可以是空数组）
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $orders->admin_name,
                'status' => 0, // 审核状态 0 待审核 1审批通过 2 审批驳回  3作废 4  删除
                'initiator_admin_name' => $orders->admin_name, // 审批发起人
                'sales_order_sn' => $param['order_sn'],
                'describe' => '待' . $admin_ids . '审核',

            ];
            $res = WaSalesOrdersExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return IndexController::errored($res, '创建订单审批日志失败');
            }
            IndexController::logSuccessed('orderSubmitApprove-massage','111111111111111111122222',$adminId);

            IndexController::logSuccessed('orderSubmitApprove-massage','销售订单发起审批消息通知',$adminId);
            $time = date('H:i:s', time());
            $time = date('H:i:s', time());
            // 钉钉消息通知
            $admin_ids = json_decode($admin_ids);
            if ($admin_ids){
                foreach ($admin_ids as $kadmin){
                    $admin_condition = [];
                    $admin_condition [] = ['id','=',$kadmin];
                    $admin_data = WaAdmins::find($admin_condition);
                    $admin_data = json_decode($admin_data);
                    $data = [
                        'mobile' => $admin_data->mobile,
                        'title' => '销售订单审批', // 标题
                        'markdown' => '有一条销售订单'. $param['order_sn'] . '需要(轮到)你帮忙审批/'.$time, // 内容
                    ];
                    IndexController::logSuccessed('orderSubmitApprove-massage','222222222223333333333',$adminId);
                    IndexController::logSuccessed('orderSubmitApprove-massage',$data,$adminId);
                    $currentRoute  = $request->host();
                    IndexController::logSuccessed('orderSubmitApprove-massage','3333333333444444444444444',$adminId);

                    IndexController::logSuccessed('orderSubmitApprove-massage','路由'.$currentRoute,$adminId);
                    IndexController::logSuccessedtest('orderSubmitApprove-massage','路由'.$currentRoute,$adminId);

                    // 消息通知
                    if ( $currentRoute == 'frontforeign.olivenev.com'){
                        IndexController::logSuccessed('orderSubmitApprove-massage','444444444444444555555555',$adminId);
                        IndexController::logSuccessed('orderSubmitApprove-massage',$data,$adminId);
                        $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                    }
                }

            }


            // 钉钉消息通知 - 销订发起审批通知(抄送)
                if ($send_before){
                    $admin_ids = $send_before;
                    foreach ($admin_ids as $kadmin){
                        $admin_condition = [];
                        $admin_condition [] = ['id','=',$kadmin];
                        $admin_data = WaAdmins::find($admin_condition);
                        $admin_data = json_decode($admin_data);
                        $data = [
                            'mobile' => $admin_data->mobile,
                            'title' => '销订发起审批通知', // 标题
                            'markdown' => '有一条由'.$adminId->nickname.'发起的销售审批订单'. $param['order_sn'] . '/'.$time, // 内容
                        ];
                        IndexController::logSuccessed('orderSubmitApprove-massage','222222222223333333333',$adminId);
                        IndexController::logSuccessed('orderSubmitApprove-massage',$data,$adminId);
                        $currentRoute  = $request->host();
                        IndexController::logSuccessed('orderSubmitApprove-massage','3333333333444444444444444',$adminId);

                        IndexController::logSuccessed('orderSubmitApprove-massage','路由'.$currentRoute,$adminId);
                        IndexController::logSuccessedtest('orderSubmitApprove-massage','路由'.$currentRoute,$adminId);

                        // 消息通知
                        if ( $currentRoute == 'frontforeign.olivenev.com'){
                            IndexController::logSuccessed('orderSubmitApprove-massage','444444444444444555555555',$adminId);
                            IndexController::logSuccessed('orderSubmitApprove-massage',$data,$adminId);
                            $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                        }
                    }

                }

//


            \support\Db::commit();
            return IndexController::successed($res, '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderSubmitApprove', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 更新-确认完成采购
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmCompletionProcurement(Request $request)
    {
        PublicCommentController::销售订单状态;
        // 订单状态 5 订单采购中
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }


        PublicCommentController::销售订单状态;
        if ($status != 5) {
            return IndexController::errored('', '订单采购中状态才能确认完成采购');
        }
        if (!$param['children_data']) {
            return IndexController::errored('', '无法获取销售订单产品信息');
        }

        \support\Db::beginTransaction();
        try {
            //添加车架号确认日志
            if ($param['children_data']) {
                //判断是否全部采购完
                $not_vin_count_all = 0;

                foreach ($param['children_data'] as $k) {

                    $children_data = WaOrdersRelevance::find(['order_sn_child' => $k['children_sn']]);
                    $children_data = json_decode($children_data);
                    if (!$children_data) {
                        return IndexController::errored('', '获取补单子订单信息');
                    }


                    $chil_count = $children_data->count;// 当前产品需要的数量
                    $vin_count = count($k['vins']); // 入参的车架号数量
                    $not_vin_count = $chil_count - $vin_count; // 未确认数量
                    if ($not_vin_count) {
                        $not_vin_count_all = $not_vin_count_all + $not_vin_count; // 全部待配车数量统计
                    }
                    // 更新车架号到销售订单对应子订单
                    $orders_relevance_where = [];
                    $orders_relevance_where [] = ['order_sn_child', '=', $k['children_sn']];

                    $orders_relevance_data = [
                        'vin' => json_encode($k['vins']), // 车架号
                        'vin_count' => $vin_count, // 入参的车架号数量
                        'updated_at' => dateTime(),
                    ];
                    $orders_relevance_up = WaOrdersRelevance::updated($orders_relevance_data, $orders_relevance_where);
                    if (!$orders_relevance_up) {
                        return IndexController::errored('', '销售订单子订单状态修改失败');
                    }
                }


                // 当所有 待配车数量为 0 时才修改订单状态为 13 待报关
                if (!$not_vin_count_all) {
                    foreach ($param['children_data'] as $k) {
                        foreach ($k['vins'] as $kv) {

                            //创建子订单配车信息
                            $vin_code = WaOrdersOperateLogVin::find(['vin' => $kv]);
                            $vin_code = json_decode($vin_code);
                            if ($vin_code) {
                                return IndexController::errored($kv, '车架号已存在');
                            }

                            // 通过车架号查询 车务中的信息
                            $purchased_vehicles = WaPurchasedVehicles::find(['vin' => $kv['vin']]);
                            $purchased_vehicles = json_decode($purchased_vehicles);
                            if (!$purchased_vehicles) {
                                return IndexController::errored($kv['vin'], '已采购车辆中车架号信息不存在');
                            }

                            $vin_data = [
                                'admin_id' => $adminId->id,
                                'admin_name' => $adminId->nickname,
                                'created_at' => dateTime(),
                                'vin' => $kv['vin'],
                                'order_sn_children' => $k['children_sn'],
                                'purchase_order_sn' => $purchased_vehicles->purchase_order_sn,
//                                'product_no' => $purchased_vehicles->product_no,
//                                'product_type' => $purchased_vehicles->product_type,
                                'brands_name' => $purchased_vehicles->brands_name,
//                                'car_type' => $purchased_vehicles->car_type,
                                'series_name' => $purchased_vehicles->series_name,
                                'model' => $purchased_vehicles->model,
                                'order_sn_parent' => $param['order_sn'],
                            ];

                            $log_vin = WaOrdersOperateLogVin::created($vin_data);
                            if (!$log_vin) {
                                return IndexController::errored('', '销售订单确认完成采购车架号入录添加错误');
                            }

                            // 销售订单确认完成采购操作日志
                            $data_log = [
                                'status' => 1,
                                'describe' => '销售订单' . $param['order_sn'] . '确认完成采购',
                                'admin_id' => $adminId->id,
                                'admin_name' => $adminId->nickname,
                                'created_at' => dateTime(),
                            ];
                            $data_log_add = WaOrdersOperateLog::created($data_log);
                            if (!$data_log_add) {
                                return IndexController::errored('', '销售订单确认完成采购操作日志添加错误');
                            }


                            // 更新 已采购车辆使用情况
                            $where_purchased_vehicles = [];
                            $where_purchased_vehicles [] = ['vin', '=', $kv['vin']];
                            $purchased_vehicles_data = [
                                'sales_order_sn' => $param['order_sn'],
                                'sales_children_sn' => $k['children_sn'],
                                'confirm_status' => 2,
                                'updated_at' => dateTime()
                            ];
                            $confirm_status = WaPurchasedVehicles::updated($where_purchased_vehicles, $purchased_vehicles_data);
                            if (!$confirm_status) {
                                return IndexController::errored($kv, '已采购车辆使用状态修改失败');
                            }
                        }

                    }

                    //更新订单状态
                    PublicCommentController::销售订单状态;
                    $status_up = WaOrders::updated(['status' => 19, 'updated_at' => dateTime()], ['order_sn' => $param['order_sn']]);
                    if (!$status_up) {
                        return IndexController::errored($status_up, '状态更新失败');
                    }
                }


            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('confirmCompletionProcurement', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 销售订单-客户确认签署
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function customerConfirmSigning(Request $request)
    {
        PublicCommentController::销售订单状态;
        // 订单状态  17 待客户确认签署
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != true){
            return IndexController::errored('',$status_check);
        }
        if ($status != 3) {
            return IndexController::errored('', '待生成销售合同状态才能修改待客户确认签署');
        }

        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $status = 4; //  待客户确认签署
            $describe = $adminId->nickname . '待生成销售合同' . $param['order_sn'] . '状态修改为待客户确认签署';
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payer_name' => '',
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];
            $order_data = [
                'status' => $status,
                'updated_at' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }
            $order_where = [];
            $order_where [] = ['order_sn', '=', $param['order_sn']];
            $order_status_up = WaOrders::updated($order_data, $order_where);
            if ($order_status_up != 'true') {
                return IndexController::errored($order_status_up, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('customerConfirmSigning', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     *销售订单-生成合同
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function generateContract(Request $request)
    {
        PublicCommentController::销售订单状态;
        // 订单状态  3 待生成合同
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = OrderController::status($param['order_sn']);
        if ($status != 3) {
            return IndexController::errored('', '待生成销售合同状态才能修改待客户确认签署');
        }

        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $status = 17; //  待客户确认签
            $describe = $adminId->nickname . '待生成销售合同' . $param['order_sn'] . '状态修改为待客户确认签署';
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payer_name' => '',
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];
            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('generateContract', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * PI上传
     * @param Request $request
     */
    public function orderUploadPi(Request $request)
    {
        // 订单状态 1审批中
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
//        $status = OrderController::status($param['order_sn']);
        //销售订单状态
        if(!$param['pi']){
            return IndexController::errored('', 'PI数据不能为空');
        }
        $data_order = [
            'pi' => json_encode($param['pi']),
            'updated_at' => dateTime(),
        ];

        $data_where = [];
        $data_where [] = ['order_sn', '=', $param['order_sn']];
        $order_up = WaOrders::updated($data_order, $data_where);
        if (!$order_up) {
            return IndexController::errored('', 'pi更新失败');
        }


        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $voucher = json_encode($param['pi']);
//            $remark = $param['remark'];
            $describe = $adminId->nickname . '更新' . $param['order_sn'] . 'pi';
            // 销售订单操作日志
            $data_log = [
                'order_sn_parent' => $param['order_sn'],
                'status' => 0,
                'describe' => $describe,
                'remark' => '',
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data_log, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderUploadPi', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 销售合同-确认签署 （上传合同）
     * @param Request $request
     * @return Response
     */
    public function orderContractConfirmSigning(Request $request)
    {
        // 订单状态 1审批中
        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
        //销售订单状态
        PublicCommentController::销售订单状态;
        if (!in_array($status,[17])) {
            return IndexController::errored('', '只有待签署合同状态状态可以修改');
        }


        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $voucher = $param['confirm_signing'];
//            $remark = $param['remark'];
            $status = 5; //  采购中
            $describe = $adminId->nickname . '确认签署合同' . $param['order_sn'] . '状态修改为订单采购中(未设置定金)';

            //订单数据
            $order_condition = [];
            $order_condition [] = ['order_sn','=',$param['order_sn']];
            $order_date = WaOrders::find($order_condition);
            $order_date = json_decode($order_date);
            if (!$order_date){
                return IndexController::errored('','订单数据获取失败');
            }

            // 修改销售订单状态
            $data_order = [
                'confirm_signing' => $param['confirm_signing'],
                'status' => $status, // 待支付定金
                'updated_at' => dateTime(),
            ];

            $data_where = [];
            $data_where [] = ['order_sn', '=', $param['order_sn']];
            $order_up = WaOrders::updated($data_order, $data_where);
            if (!$order_up) {
                return IndexController::errored('', '订单信息更新失败');
            }



            // 销售订单操作日志
            $data_log = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => '',
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
            ];

            $order_log = self::ordersOperateLog($data_log, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderContractConfirmSigning', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 销售订单列表
     * @param Request $request
     * @return Response
     */
    public function salesOrderList(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $between = [];
        $whereNotIn = [11];
        $whereIn = []; // 业务部人员 （只能看自己的订单）
        $whereStatusIn = []; // 状态
        // 数据权限 1 默认全部  2 只看自己
        if ($adminId->data_permission == 2) {
            $condition [] = ['admin_id', '=', $adminId->id];
        }
        if ($param['order_sn']) {
            $condition [] = ['order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }

        if ($param['user_name']) {
            $condition [] = ['admin_name', 'like', '%' . $param['user_name'] . '%'];
        }

//        if ($param['status'] || $param['status'] == 0) {
//            $condition [] = ['status', '=', $param['status']];
//        }
        if ($param['status']) {
            $whereStatusIn = $param['status'];
        }
        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        if (in_array($adminId->department_id, [42, 43])) { // 海外业务部一组 海外业务部二组
            $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
            $whereIn = $next_epartment_members;
        }

//        // 财务
//        if ($adminId->department_id == 38) {
//            $condition [] = ['status', '=', 12];
//            $whereIn = [];
//        }
//        // 跟单
//        //判断是否是跟单人员进来 是否跟单人员 0 不是 1 是
//        if ($adminId->is_merchandiser == 1){
//            // 获取绑定当前跟单人员的 业务员
//            $admins = WaAdmins::allId(['id'],['merchandiser_id' => $adminId->id]);
//            $admins = json_decode($admins);
////            if ($admins){
////                foreach ($admins as $ka){
////                    array_push($whereIn,$ka->id);
////                }
////            }
////            $condition [] = ['status', '=', 1];
//            $whereIn = [];
//        }
        $pageNum = $param['pageNum'];
        $fields = ['*'];
        $page = $param['page'];
        $listOrder = WaOrders::list($adminId, $page, $pageNum, $whereIn, $whereNotIn, $fields, $whereStatusIn, $condition, $between);


        return IndexController::successed($listOrder, '销售订单列表');

    }

    /**
     * 销售订单列表-不分页
     * @param Request $request
     * @return Response
     */
    public function salesOrderAll(Request $request)
{
    $param = $request->all();
    $adminId = json_decode(adminId($request));
    $condition = [];
    $between = [];
    // 数据权限 1 默认全部  2 只看自己
    if ($adminId->data_permission == 2) {
        $condition [] = ['admin_id', '=', $adminId->id];
    }
    if (array_key_exists('user_id', $param)) {
        if ($param['user_id']) {
            $condition [] = ['user_id', '=', $param['user_id'] ];
        }
    }
    if (array_key_exists('currency', $param)) {
        if ($param['currency']) {
            $condition [] = ['currency', '=', $param['currency'] ];
        }
    }

    if (array_key_exists('order_sn', $param)) {
        if ($param['order_sn']) {
            $condition [] = ['order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }
    }
    if (array_key_exists('status', $param)) {
        if ($param['status']) {
            $condition [] = ['status', '=', $param['status']];
        } else {
            $condition [] = ['status', '=', 5]; // 采购中
        }
    }
    $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
    $whereIn = $next_epartment_members;
    if (!$whereIn) {
        $whereIn = [];
    }


    $con_one = [];
    $con_two = [];
    $con_three = [];
    $con_four = [];
    if (array_key_exists('like_name', $param)) {
        if ($param['like_name']) {
            $con_one [] = ['brands_name', 'like', '%' . $param['like_name'] . '%'];
            $con_one [] = ['order_sn_parent', '=', ''];
//                $con_two [] = ['car_type', 'like', '%' . $param['like_name'] . '%'];
            $con_two [] = ['order_sn_parent', '=', ''];
            $con_three [] = ['series_name', 'like', '%' . $param['like_name'] . '%'];
            $con_three [] = ['order_sn_parent', '=', ''];
            $con_four [] = ['model', 'like', '%' . $param['like_name'] . '%'];
            $con_four [] = ['order_sn_parent', '=', ''];
            $listOrder = WaOrders::allByLike($condition, $con_one, $con_two, $con_three, $con_four);
        } else {
            $listOrder = WaOrders::alls($condition);
        }
    } else {
        $listOrder = WaOrders::alls($condition);
    }


    return IndexController::successed($listOrder, '销售订单不分页列表');

}

    /**
     * 销售订单列表-不分页 - 账单列表专用
     * @param Request $request
     * @return Response
     */
    public function salesOrderAllByAccInfo(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $between = [];
        // 数据权限 1 默认全部  2 只看自己
        if ($adminId->data_permission == 2) {
            $condition [] = ['admin_id', '=', $adminId->id];
        }
        if (array_key_exists('user_id', $param)) {
            if ($param['user_id']) {
                $condition [] = ['user_id', '=', $param['user_id'] ];
            }else{
                return IndexController::errored($param['user_id'], '缺少用户id,需要重新选择');
            }
        }
        if (array_key_exists('currency', $param)) {
            if ($param['currency']) {
                $condition [] = ['currency', '=', $param['currency'] ];
            }
        }
        PublicCommentController::销售订单状态;


        $where_in = [5,9,17,19];
        $listOrder = WaOrders::allsByWhereIn($condition,$where_in);


        return IndexController::successed($listOrder, '销售订单不分页列表');

    }




    /**
     * 销售订单产品信息
     * @param Request $request
     * @return Response
     */
    public function salesOrderProducts(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $condition [] = ['order_sn', '=', $param['order_sn_parent']];
//        $orderParentData = WaOrders::find($condition);
        $orderParentData = WaOrders::findApprove($adminId, $condition);

        if (!$orderParentData) {
            IndexController::errored('', '主订单信息获取失败');
        }
        $orderParentData = json_decode($orderParentData);
        if ($orderParentData->pi) {
            $orderParentData->pi = json_decode($orderParentData->pi);
        }
        if ($orderParentData->transfer_export_company_account) {
            $orderParentData->transfer_export_company_account = json_decode($orderParentData->transfer_export_company_account);
        }

        if ($orderParentData->pi) {
            $orderParentData->pi = json_decode($orderParentData->pi);
        }

//
//        $condition_by_order = [];
//        $condition_by_order [] = ['order_sn', '=', $param['order_sn_parent']];
//        $orderDataByOrder = WaOrders::find($condition_by_order);
//        if (!$orderDataByOrder) {
//            IndexController::errored('', '主订单信息获取失败');
//        }



        // 客户类型
        if ($orderParentData->user_type) {
            $condition_admin = [];
            $condition_admin [] = ['id', '=', $orderParentData->admin_id];
            $adminData = WaAdmins::find($condition_admin);
            $adminData = json_decode($adminData);

            $orderParentData->admin_english_name = $adminData->english_name; // 管理员
            $orderParentData->admin_username = $orderParentData->admin_name; // 管理员
            $orderParentData->admin_email = $adminData->email; // 管理员
            $orderParentData->admin_mobile = $adminData->mobile; // 管理员
            $orderParentData->customer_username = $orderParentData->user_name;// 客户
            $orderParentData->customer_email = $orderParentData->email; // 客户
            $orderParentData->customer_mobile = $orderParentData->phone; // 客户
            $orderParentData->customer_address = $orderParentData->address; // 客户

            if ($orderParentData->user_type == 1) {
                $orderParentData->user_type_name = '个人';
            } elseif ($orderParentData->user_type == 2) {
                $orderParentData->user_type_name = '企业';
            } else {
                $orderParentData->user_type_name = '';
            }

            // 1 汽运、2 铁路、海运(3 集装箱、4 滚装船)
            if ($orderParentData->shipment == 1) {
                $orderParentData->shipment_name = '汽运';
            } elseif ($orderParentData->shipment == 2) {
                $orderParentData->shipment_name = '铁路';
            } elseif ($orderParentData->shipment == 3) {
                $orderParentData->shipment_name = '海运集装箱';
            } elseif ($orderParentData->shipment == 4) {
                $orderParentData->shipment_name = '海运滚装船';
            } else {
                $orderParentData->shipment_name = '';
            }

        }
        $listOrder = [];// 当前订单的详情数据
        $condition_parent = [];
        $condition_parent [] = ['order_sn_parent', '=', $param['order_sn_parent']];
        $orderChildren = WaOrdersRelevance::all($condition_parent);
        $orderChildren = json_decode($orderChildren);
        if ($orderChildren) {
            $condi = [];
            foreach ($orderChildren as $k) {
                //  查询采购车辆中绑定的该订单的车架号
                $purchased_vehicles_vins = [];
                $purchased_vehicles_vins [] = ['sales_children_sn', '=', $k->order_sn_child];

                // 上牌服务商
                if ($k->registration_id) {
                    $registration_fee = WaSupplierRegistrationFee::find(['id' => intval($k->registration_id)]);
                    $registration_fee = json_decode($registration_fee);
                    if ($registration_fee) {
                        $k->registration_name = $registration_fee->name;
                    } else {
                        $k->registration_name = '';
                    }

                } else {
                    $k->registration_name = '';
                }

                // 转移待出口服务商
                if ($k->transfer_export_id) {
                    $transfer_export_fee = WaSupplierRegistrationFee::find(['id' => intval($k->transfer_export_id)]);
                    $transfer_export_fee = json_decode($transfer_export_fee);
                    if ($transfer_export_fee) {
                        $k->transfer_export_name = $transfer_export_fee->name;
                    } else {
                        $k->transfer_export_name = '';
                    }

                } else {
                    $k->transfer_export_name = '';
                }
                $condi [] = ['order_sn_parent', '=', $k->order_sn_child];
                $vins = WaOrdersOperateLogVin::geted(['vin'], $condi);
//                if ($vins) {
//                    $vins = json_encode($vins);
//                    $k->vins = $vins;
//                } else {
//                    $k->vins = [];
//                }
                // 产品类型 1 预售待采购 2 库存待销售 3部分预售单（两者都有）
                if ($k->product_type == 1) {
                    $k->product_type_name = '预售待采购';
                } elseif ($k->product_type == 2) {
                    $k->product_type_name = '库存待销售';
                } elseif ($k->product_type == 3) {
                    $k->product_type_name = '部分预售单（两者都有）';
                } else {
                    $k->product_type_name = '';
                }


                // 1 轿车 2 SUV 3 MPV 4 跑车 5 新能源
                if ($k->car_type == 1) {
                    $k->car_type_name = '轿车';
                } elseif ($k->car_type == 2) {
                    $k->car_type_name = 'SUV';
                } elseif ($k->car_type == 3) {
                    $k->car_type_name = 'MPV';
                } elseif ($k->car_type == 4) {
                    $k->car_type_name = '跑车';
                } elseif ($k->car_type == 5) {
                    $k->car_type_name = '新能源';
                } else {
                    $k->car_type_name = '';
                }


                $children_data = WaPurchasedVehicles::all(['*'], $purchased_vehicles_vins);
                $children_data = json_decode($children_data);
                $vins = [];
                if ($children_data) {
                    foreach ($children_data as $kd) {
                        if ($kd->voucher) {
                            $voucher = $kd->voucher;
                        } else {
                            $voucher = null;
                        }
                        $v_da = [
                            'remark' => $kd->remark,
                            'vin' => $kd->vin,
                            'voucher' => $voucher
                        ];
                        array_push($vins, $v_da);
                    }
                }
                $k->children_sn = $k->order_sn_child;
                $k->vins = $vins;

            }
            $listOrder['orderChildren'] = $orderChildren;  // 当前订单子订单详情列表 (产品信息)
            $listOrder['orderParentData'] = $orderParentData; //  当前订单主订单的详情信息

            PublicCommentController::销售订单状态;
            //  收款信息
            $where = [];
            $fields = ['*'];
            $where [] = ['order_sn_parent', '=', $param['order_sn_parent']];
//            $whereIn = [4,6];
            $confirm_pay = WaAccountingInformation::all($fields,$where);
            if ($confirm_pay) {
                $confirm_pay = json_decode($confirm_pay);
            }
            $listOrder['confirm_pay'] = $confirm_pay; // 支付信息 / 收款信息

            // 车辆信息（采购入库）
            // 1 待入库 2 已入库 3 待支付交强险 4 待上牌  5 待开二手票 6 转移待出口 7 已注销 8 入库失败
            $where_pay = [];
            $where_pay [] = ['order_sn_parent', '=', $param['order_sn_parent']];
            $vehicle_info = WaOrdersOperateLogVin::all($where_pay);
//            $vehicle_info = WaPurchasedVehicles::all(['*'], $where_pay);
            if ($vehicle_info) {
                $vehicle_info = json_decode($vehicle_info);
            }

            $listOrder['vehicle_info'] = $vehicle_info;

            // 发货信息 confirmShipment confirmReceipt
            $condition_shipment = [];
            $condition_shipment [] = ['status', '=', 7];
            $condition_shipment [] = ['order_sn_parent', '=', $param['order_sn_parent']];
            $confirm_shipment_info = WaOrdersOperateLog::find(['*'], $condition_shipment);
            if ($confirm_shipment_info) {
                $confirm_shipment_info = json_decode($confirm_shipment_info);
            }

            $listOrder['confirm_shipment_info'] = $confirm_shipment_info;
            // 收货信息
            $condition_receipt = [];
            $condition_receipt [] = ['status', '=', 8];
            $condition_receipt [] = ['order_sn_parent', '=', $param['order_sn_parent']];
            $confirm_receipt_info = WaOrdersOperateLog::find(['*'], $condition_receipt);
            if ($confirm_receipt_info) {
                $confirm_receipt_info = json_decode($confirm_receipt_info);
            }
            $listOrder['confirm_receipt_info'] = $confirm_receipt_info;

            // 报关信息
            // 订单状态 0 草稿  2审批中   3 待生成销售合同(弃用)   4 待支付定金 12 财务确认到账 5 订单采购中  13 待报关 7待发货   6待支付余款  8待收货  15 交付提单（交车） 9已完成 10 已作废 11 删除  17 待客户确认签署 18 审批驳回
            $condition_declare = [];
            $condition_declare [] = ['status', '=', 7];
            $condition_declare [] = ['order_sn_parent', '=', $param['order_sn_parent']];
            $condition_declare_info = WaOrdersOperateLog::find(['*'], $condition_declare);
            if ($condition_declare_info) {
                $condition_declare_info = json_decode($condition_declare_info);
            }
            $listOrder['condition_declare_info'] = $condition_declare_info;

            $accounting_info = WaAccountingInformationRelevance::all(['*'],[['order_sn_parent','=',$param['order_sn_parent']],['status','=',1]]);
            if ($accounting_info){
                $accounting_info = json_decode($accounting_info);
            }
            $listOrder['accounting_info'] = $accounting_info;

            $listOrder = json_encode($listOrder);
        }


        return IndexController::successed($listOrder, '销售订单产品信息');

    }

    /**
     * 关联销售订单列表
     * 选择状态为 待签署销售合同，且一个销售订单只允许被一份合同关联
     * @param Request $request
     * @return Response
     */
    public function orderByStatus(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $condition = [];
        if ($param['order_sn']) {
            $condition [] = ['order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }
        $condition [] = ['status', '=', 3];
        $res = WaOrders::alls($condition);
        return IndexController::successed($res, '关联销售订单列表');

    }


    /**
     * 销售订单-合并订单
     * @param Request $request
     */
    public function ordermMerge(Request $request)
    {
        process($request);
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));

        // 销售订单编号
        $sn = IndexController::generateOrderSn();

        // 今天开始时间
        $todayStart = strtotime("today");

        // 今天结束时间
        $todayEnd = strtotime("tomorrow") - 1;
        //获取当前用户今日的订单数量
        $admin_order_count_todady = WaOrders::ordersCountByAdmin($todayStart,$todayEnd,$adminId);
        $admin_order_count_todady = $admin_order_count_todady + 1;
        if ($admin_order_count_todady < 10){
            $admin_order_count_todady = str_pad($admin_order_count_todady, 2, '0', STR_PAD_LEFT); // 使用str_pad添加0
        }
        if (!$adminId->nickname_abbreviation){
            $adminId->nickname_abbreviation = 'TS'.$adminId->id;
        }

        // 获取今日结束时间
        $order_sn = 'WMSAL' . $sn . $adminId->nickname_abbreviation.$admin_order_count_todady; // 父订单编号 销售订单编号

        PublicCommentController::销售订单状态;

        // 父订单信息取第一条下标数据
        $condition_one = [];
        $condition_one [] = ['order_sn', '=', $param['order_sn_batch'][0]];
        $orders_parent_data = WaOrders::find($condition_one);
        $orders_parent_data = json_decode($orders_parent_data);
        if ($orders_parent_data) {
            $orders_parent_data->order_sn = $order_sn;
        }
        // 以第一个子订单 添加数据
        $condition_parent_one = [];
        $condition_parent_one [] = ['order_sn_parent', '=', $param['order_sn_batch'][0]];
        $orders_children_data = WaOrdersRelevance::all($condition_parent_one);
        $orders_children_data = json_decode($orders_children_data);


        // 子订单
//        $specs_can = [];
        // 订单必须都是 草稿状态  且 必须是同一个客户 才能合并
        if ($param['order_sn_batch']) {
            foreach ($param['order_sn_batch'] as $k) {
                $condition = [];
                $condition [] = ['order_sn', '=', $k];
                $orders = WaOrders::find($condition);
                $orders = json_decode($orders);
                if ($orders->user_id != $orders_parent_data->user_id) {
                    return IndexController::errored($orders->user_id . '+' . $orders_parent_data->user_id, '不是同一个用户的 订单不能合并');
                }

                if ($orders->currency != $orders_parent_data->currency) {
                    return IndexController::errored('', '订单汇率不同不能合并');
                }

                if ($orders->status != 0) {
                    return IndexController::errored($orders->order_sn, '不是草稿状态 订单不能合并');
                }
                $created_time = strtotime($orders->created_at);
                $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                if ($end < $created_time || $created_time < $start) {
                    return IndexController::errored($orders->order_sn, '只有当天的订单可以合并');
                }


                // 第一条的信息不需要录入
                if ($k != $param['order_sn_batch'][0]) {
                    $condition_parent = [];
                    $condition_parent [] = ['order_sn_parent', '=', $k];
                    $orders_children_by_key = WaOrdersRelevance::all($condition_parent);
                    $orders_children_by_key = json_decode($orders_children_by_key);
                    if ($orders_children_by_key) {
                        // 相同同产品 无法合并到同一条  例如 编号 选装包 交货条件 运输方式 费用选项都可能不一样  合不到一起

                        foreach ($orders_children_by_key as $ke) {
                            array_push($orders_children_data, $ke);
                        }
                    }
                }
            }
            $total_amount = 0;
            foreach ($orders_children_data as $kes) {

                $kes->order_sn_parent = $order_sn;
                $order_sn_child = 'WMXDZ' . IndexController::generateOrderSnOther(); // 子订单编号
                $kes->order_sn_child = $order_sn_child;
                $total_amount = $total_amount + round($kes->total_price, 2);
            }

            //销售订单状态
            $result = [
                'order_sn' => $orders_parent_data->order_sn, // Y
                'admin_id' => $orders_parent_data->id, // Y
                'user_id' => $orders_parent_data->user_id, // Y
                'phone' => $orders_parent_data->phone,
                'email' => $orders_parent_data->email,
                'pol' => $orders_parent_data->pol,
                'pod' => $orders_parent_data->pod,
                'pol_en' => $orders_parent_data->pol_en, // POL装港
                'pod_en' => $orders_parent_data->pod_en, // POD卸港
                'condition' => $orders_parent_data->condition,
                'specs_can' => $orders_children_data,
            ];

            $specs = $result['specs_can'];
            // 获取客户信息
            $where = [];
            $where [] = ['id', '=', $orders_parent_data->user_id];
            $member = WaMembers::find($where);
            $member = json_decode($member);
            if (!$member) {
                return IndexController::errored('', '获取客户信息失败');
            }
            PublicCommentController::销售订单状态;
            // 父订单创建

            $order_data = [
                'user_id' => $orders_parent_data->user_id, // 用户id
                'user_name' => $orders_parent_data->user_name, // 用户名称
                'country' => $orders_parent_data->country, //
                'address' => $orders_parent_data->address, //
                'phone' => $orders_parent_data->phone,
                'email' => $orders_parent_data->email,
                'user_type' => $member->type,
                'passport_number' => $member->passport_number,
                'business_license_number' => $member->business_license_number,

                'orders_type' => $orders_parent_data->orders_type, // 订单类型
                'pol' => $orders_parent_data->pol,
                'pod' => $orders_parent_data->pod,
                'pol_en' => $orders_parent_data->pol_en, // POL装港
                'pod_en' => $orders_parent_data->pod_en, // POD卸港
                'condition' => $orders_parent_data->condition,
                'cnh' => $orders_parent_data->cnh, // 美元汇率
                'currency' => $orders_parent_data->currency, // 币种 1 人民币 2 美元 3 欧元

                'deeposit_ratio' => $orders_parent_data->deeposit_ratio,// 定金比例
                'deeposit_amount' => $orders_parent_data->deeposit_amount,// 定金金额
                'consignee_name' => $orders_parent_data->consignee_name,// 收货人名称
                'consignee_document_type' => $orders_parent_data->consignee_document_type,// 收货人证件类型： 护照 营业执照号
                'consignee_document_num' => $orders_parent_data->consignee_document_num,// 收货人证件号码
                'consignee_document_phone' => $orders_parent_data->consignee_document_phone,// 收货人电话
                'consignee_document_email' => $orders_parent_data->consignee_document_email,// 收货人邮箱
                'consignee_document_address' => $orders_parent_data->consignee_document_address,// 收货人地址
                'notifier_name' => $orders_parent_data->notifier_name,// 通知人姓名
                'notifier_phone' => $orders_parent_data->notifier_phone,// 通知人电话
                'notifier_email' => $orders_parent_data->notifier_email,// 通知人邮箱
                'notifier_address' => $orders_parent_data->notifier_address,// 收货人地址
                'shipment' => $orders_parent_data->shipment, // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)
                'user_linkman' => $orders_parent_data->user_linkman, // 1 汽运、2 铁路、海运(3 集装箱、4滚装船)
                'total_amount' => $total_amount,
                'order_sn' => $order_sn,
                'admin_id' => $adminId->id, // 管理员
                'admin_name' => $adminId->nickname, // 管理员名称
                'status' => 0,
                'created_at' => dateTime(), // 创建时间

            ];
            if (array_key_exists('consignee_link_name',$param)){
                if ($param['consignee_link_name']){
                    $order_data['consignee_link_name'] = $param['consignee_link_name'];// 收货联系人姓名
                }
            }
            $quotation_order_sn = '';
            $order_sn_olds = '';
            \support\Db::beginTransaction();
            try {
                if ($specs) {
                    $ordersCreated = WaOrders::created($order_data); // 更新报价单
                    if (!$ordersCreated) {
                        return IndexController::errored('', '销售订单创建失败');
                    }

                    foreach ($specs as $k) {
                        $order_sn_child = 'WMXDZ' . IndexController::generateOrderSnOther(); // 子订单编号
                        $quotation_order_sn = $order_sn_child . ',' . $quotation_order_sn;
//                    $total_price = 0; // 总价格
                        $order_detail_data = [
                            'order_sn_parent' => $order_sn, // 父订单编号
                            'order_sn_child' => $order_sn_child, // 子订单编号

                            'product_no' => $k->product_no, // 关联产品编号
                            'product_type' => $k->product_type, // 产品类型
                            'brands_name' => $k->brands_name, // 品牌
                            'series_name' => $k->series_name, // 车系
                            'model' => $k->model, // 车型名称

                            'is_nev' => $k->is_nev, // 是否新能源 1 是 2 传统能源
                            'market_time' => $k->market_time, // 上市日期
                            'vehicle_status' => $k->vehicle_status ? round($k->vehicle_status, 2) : 0, // 车辆状况(是否是新车)  1 新车 2 二手车

                            'guide_price' => $k->guide_price ? round($k->guide_price, 2) : 0, // 指导价
                            'option_package' => json_encode($k->option_package), // 选装包
                            'option_package_price' => $k->option_package_price ? round($k->option_package_price, 2) : 0, // 选装包价格
                            'traffic_compulsory_insurance' => $k->traffic_compulsory_insurance ? round($k->traffic_compulsory_insurance, 2) : 0, // 交强险
//                            'purchase_tax' => $k->purchase_tax ? round($k->purchase_tax, 2) : 0, // 购置税


//                            'fas_base_price' => $k->fas_base_price ? round($k->fas_base_price, 2) : 0, //  底价
                            'premium_price' => $k->premium_price ? round($k->premium_price, 2) : 0, //  溢价
                            'final_offer_price' => $k->final_offer_price ? round($k->final_offer_price, 2) : 0, //  最终报价

//                            'registration_province' => $k->registration_province, //  上牌省份
//                            'registration_city' => $k->registration_city, // 上牌市
//                            'registration_area' => $k->registration_area, // 上牌区
//                            'transfer_export_province' => $k->transfer_export_province, // 转移待出口省份
//                            'transfer_export_city' => $k->transfer_export_city, // 转移待出口上牌市
//                            'transfer_export_area' => $k->transfer_export_area, // 转移待出口上牌区
//
//                            'registration_id' => $k->registration_id ? intval($k->registration_id) : 0, // 上牌服务商id
//                            'transfer_export_id' => $k->transfer_export_id ? intval($k->transfer_export_id) : 0, // 转移待出口服务商id


//                            'port_charges' => $k->port_charges ? round($k->port_charges, 2) : 0, // 集港运费
                            'port_departure_charges' => $k->port_departure_charges ? round($k->port_departure_charges, 2) : 0, // 起运港港杂费
                            'premium_charges' => $k->premium_charges ? round($k->premium_charges, 2) : 0, // 国际运输保险费
                            'international_freight' => $k->international_freight ? round($k->international_freight, 2) : 0, // 国际运费
//                            'kilometres' => $k->international_freight ? round($k->kilometres, 2) : 0, // 公里数
                            'count' => $k->count ? round($k->count, 2) : 0, // 数量
                            'to_be_purchase_count' => $k->count ? intval($k->count) : 0, // 待采购数量
                            'updated_at' => date('y-m-d h:m:s', time()), // 创建时间

                            "urban_trailer_fee" => $k['urban_trailer_fee'] ? round($k['urban_trailer_fee'], 2) : 0, // 城区拖车费
                            "domestic_storage_fees" => $k['domestic_storage_fees'] ? round($k['domestic_storage_fees'], 2) : 0, // 国内仓储费
                            "car_wash_beauty_fee" => $k['car_wash_beauty_fee'] ? round($k['car_wash_beauty_fee'], 2) : 0, // 洗车美容费
                            "used_car_check_fee" => $k['used_car_check_fee'] ? round($k['used_car_check_fee'], 2) : 0, // 二手车检测费/第三方检测费
                            "port_price" => $k['port_price'] ? round($k['port_price'], 2) : 0, // 集港物流费
                            "export_testing_fee" => $k['export_testing_fee'] ? round($k['export_testing_fee'], 2) : 0, // 出口检测费


                            'sub_brand_name' => $k->sub_brand_name, // 厂商
                            'purchase_quotation' => $k->purchase_quotation ? round($k->purchase_quotation, 2) : 0, // 行情报价
                            'purchase_price' => $k->purchase_price ? round($k->purchase_price, 2) : 0, // 二手车采购价格
                            'VAT_invoice_price' => $k->VAT_invoice_price ? round($k->VAT_invoice_price, 2) : 0, // 增值税发票金额
                            'retail_concessions' => $k->retail_concessions ? round($k->retail_concessions, 2) : 0, // 零售优惠
                            'other_rebates' => $k->other_rebates ? round($k->other_rebates, 2) : 0, // 采购返利
                            'registration_fee' => $k->registration_fee ? round($k->registration_fee, 2) : 0, //  上牌费用
                            'used_car_fee' => $k->used_car_fee ? round($k->used_car_fee, 2) : 0, //  二手车过户费用
                            'transfer_export_fee' => $k->transfer_export_fee ? round($k->transfer_export_fee, 2) : 0, // 转移待出口费用
                            'total_price' => $k->total_price ? round($k->total_price, 2) : 0,
                            'price_options' => json_encode($k->price_options), // 费用选项
                            'seat_count' => $k->seat_count, // 座位数
                            'car_year' => $k->car_year, //  车辆年款
                            'jb' => $k->jb, // 级别
                            'series_type' => $k->series_type, // 车身类型
                            'driver_form' => $k->driver_form, // 驱动方式
                            'length' => $k->length, // 长
                            'width' => $k->width, // 宽
                            'height' => $k->height, // 高
                            'curb_weight' => $k->curb_weight, // 设计重量
                            'resource_service_fee' => $k->resource_service_fee, // 资源服务费
                            'color_interior' => $k->color_interior, // 内饰颜色
                            'color_exterior' => $k->color_exterior, // 外观颜色
                            'model_en' => $k->model_en, //
                            'series_name_en' => $k->series_name_en, // 车系
                            'brands_name_en' => $k->brands_name_en, // 品牌
                            'fuel_form_en' => $k->fuel_form_en, // 能源类型
                            'color_interior_en' => $k->color_interior_en, // 内饰颜色
                            'color_exterior_en' => $k->color_exterior_en, // 外观颜色
                            'sub_brand_name_en' => $k->sub_brand_name_en, // 厂商

                        ];
                        if (array_key_exists('other_price',$k)){
                            if ($k['other_price']){
                                $order_detail_data['other_price'] = json_encode($k['other_price']); // 其它费用
                            }
                        }

                        if (array_key_exists('other_price_total',$k)){
                            if ($k['other_price_total']){
                                $order_detail_data['other_price_total'] = round($k['other_price_total'],2); // 其它费用总额
                            }
                        }

                        if (array_key_exists('invoice_price',$k)){
                            if ($k['invoice_price']){
                                $order_detail_data['invoice_price'] = $k['invoice_price']; // 机动车专用发票价
                            }
                        }


                        $order_detail_id = WaOrdersRelevance::created($order_detail_data); // 创建订单详情
                        if (!$order_detail_id) {
                            return IndexController::errored($order_detail_id, '创建子订单失败');
                        }
                    }


                } else {
                    return IndexController::errored($specs, '更新失败，参数值为空');
                }

                $order_data_up = [
                    'quotation_order_sn' => $quotation_order_sn,
                    'updated_at' => dateTime()
                ];
                $condition_order = [];
                $condition_order [] = [
                    'order_sn', '=', $order_sn
                ];
                $ordersUp = WaOrders::updated($order_data_up, $condition_order); // 更新报价单
                // 作废对应销售订单
                if ($param['order_sn_batch']) {
                    foreach ($param['order_sn_batch'] as $ko) {
                        $orders_status_data = [
                            'status' => 10,
                            'updated_at' => dateTime()
                        ];
                        $orders_condition = [];
                        $orders_condition [] = ['order_sn', '=', $ko];
                        $orders_status_up = WaOrders::updated($orders_status_data, $orders_condition);
                        if (!$orders_status_up) {
                            return IndexController::errored($orders_status_up, '日志添加失败失败');
                        }

                    }
                }
                // 作废日志添加
                $describe = $adminId->nickname . '旧订单' . json_encode($param['order_sn_batch']) . '合并到新订单' . $order_sn;
                $status = 10; // 作废
                // 销售订单操作日志
                $data_order_log = [
                    'order_sn_parent' => $order_sn,
                    'status' => $status,
                    'describe' => $describe,
                    'remark' => '',
                    'reason' => '',
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'payer_name' => '',
                    'created_at' => dateTime(),
                ];
                $ordersOperateLog = WaOrdersOperateLog::created($data_order_log);
                if (!$ordersOperateLog) {
                    return IndexController::errored($ordersOperateLog, '日志添加失败失败');
                }


                $da_price_name = [];
                if ($param['order_sn_batch']) {
                    $sales_order_amount_detail = WaOrdersSalesAmountDetail::allSalesOrderIn($param['order_sn_batch']);
                    $bill_details = json_decode($sales_order_amount_detail);
                    $total_amount_hang = 0;
                    $total_amount_xuan = 0;
                    $total_amount_ling = 0;
                    $total_amount_xin = 0;
                    $total_amount_er = 0;
                    $total_amount_gou = 0;
                    $total_amount_cai = 0;
                    $total_amount_jiao = 0;
                    $total_amount_shang = 0;
                    $total_amount_gouhu = 0;
                    $total_amount_zhuan = 0;
                    $total_amount_qi = 0;
                    $total_amount_tui = 0;
                    $total_amount_gang = 0;
                    $total_amount_guonei = 0;
                    $total_amount_guowai = 0;
                    //添加销售订单账单明细
                    if ($bill_details) {
                        foreach ($bill_details as $kd) {
                            if ($kd->price_name == '行情报价') {
                                $total_amount_price = $total_amount_hang + round($kd->total_amount, 2);
                                $total_amount_hang_data = [
                                    'price_name' => '行情报价',
                                    'total_amount' => $total_amount_price,
                                ];
                            }
                            if ($kd->price_name == '选装包总价格') {
                                $total_amount_xuan = $total_amount_xuan + round($kd->total_amount, 2);
                                $total_amount_xuan_data = [
                                    'price_name' => '选装包总价格',
                                    'total_amount' => $total_amount_xuan,
                                ];
                            }
                            if ($kd->price_name == '零售优惠') {
                                $total_amount_ling = $total_amount_ling + round($kd->total_amount, 2);
                                $total_amount_ling_data = [
                                    'price_name' => '零售优惠',
                                    'total_amount' => $total_amount_ling,
                                ];
                            }
                            if ($kd->price_name == '新车采购价格') {
                                $total_amount_xin = $total_amount_xin + round($kd->total_amount, 2);
                                $total_amount_xin_data = [
                                    'price_name' => '新车采购价格',
                                    'total_amount' => $total_amount_xin,
                                ];
                            }
                            if ($kd->price_name == '二手车采购价格') {
                                $total_amount_er = $total_amount_er + round($kd->total_amount, 2);
                                $total_amount_er_data = [
                                    'price_name' => '二手车采购价格',
                                    'total_amount' => $total_amount_er,
                                ];
                            }
                            if ($kd->price_name == '购置税') {
                                $total_amount_gou = $total_amount_gou + round($kd->total_amount, 2);
                                $total_amount_gou_data = [
                                    'price_name' => '购置税',
                                    'total_amount' => $total_amount_gou,
                                ];
                            }
                            if ($kd->price_name == '采购返利') {
                                $total_amount_cai = $total_amount_cai + round($kd->total_amount, 2);
                                $total_amount_cai_data = [
                                    'price_name' => '采购返利',
                                    'total_amount' => $total_amount_cai,
                                ];
                            }
                            if ($kd->price_name == '交强险') {
                                $total_amount_jiao = $total_amount_jiao + round($kd->total_amount, 2);
                                $total_amount_jiao_data = [
                                    'price_name' => '交强险',
                                    'total_amount' => $total_amount_jiao,
                                ];
                            }
                            if ($kd->price_name == '上牌费用') {
                                $total_amount_shang = $total_amount_shang + round($kd->total_amount, 2);
                                $total_amount_shang_data = [
                                    'price_name' => '上牌费用',
                                    'total_amount' => $total_amount_shang,
                                ];
                            }
                            if ($kd->price_name == '二手车过户费用') {
                                $total_amount_gouhu = $total_amount_gouhu + round($kd->total_amount, 2);
                                $total_amount_gouhu_data = [
                                    'price_name' => '二手车过户费用',
                                    'total_amount' => $total_amount_gouhu,
                                ];
                            }
                            if ($kd->price_name == '转移待出口费用') {
                                $total_amount_zhuan = $total_amount_zhuan + round($kd->total_amount, 2);
                                $total_amount_zhuan_data = [
                                    'price_name' => '转移待出口费用',
                                    'total_amount' => $total_amount_zhuan,
                                ];
                            }
                            if ($kd->price_name == '其他费用') {
                                $total_amount_qi = $total_amount_qi + round($kd->total_amount, 2);
                                $total_amount_qi_data = [
                                    'price_name' => '其他费用',
                                    'total_amount' => $total_amount_qi,
                                ];
                            }
                            if ($kd->price_name == '退税') {
                                $total_amount_tui = $total_amount_tui + round($kd->total_amount, 2);
                                $total_amount_tui_data = [
                                    'price_name' => '退税',
                                    'total_amount' => $total_amount_tui,
                                ];
                            }
                            if ($kd->price_name == '港杂费用') {
                                $total_amount_gang = $total_amount_gang + round($kd->total_amount, 2);
                                $total_amount_gang_data = [
                                    'price_name' => '港杂费用',
                                    'total_amount' => $total_amount_gang,
                                ];
                            }
                            if ($kd->price_name == '国际运费') {
                                $total_amount_guonei = $total_amount_guonei + round($kd->total_amount, 2);
                                $total_amount_guonei_data = [
                                    'price_name' => '国际运费',
                                    'total_amount' => $total_amount_guonei,
                                ];
                            }
                            if ($kd->price_name == '国际运输保险费用') {
                                $total_amount_guowai = $total_amount_guowai + round($kd->total_amount, 2);
                                $total_amount_guowai_data = [
                                    'price_name' => '国际运输保险费用',
                                    'total_amount' => $total_amount_guowai,
                                ];
                            }
                        }
                    }
                    $sales_where = [];
                    $sales_where [] = ['sales_order_sn', '=', $param['order_sn_batch'][0]];
                    $sales_order_amount_detail_zero = WaOrdersSalesAmountDetail::all($sales_where);
                    $sales_order_amount_detail_zero = json_decode($sales_order_amount_detail_zero);
                    if ($sales_order_amount_detail_zero) {
                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '行情报价') {
                                $ksa->total_amount = $total_amount_hang_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 行情报价 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '选装包总价格') {
                                $ksa->total_amount = $total_amount_xuan_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 选装包总价格 失败');
                                }
                            }

                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '零售优惠') {
                                $ksa->total_amount = $total_amount_ling_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 零售优惠 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '新车采购价格') {
                                $ksa->total_amount = $total_amount_xin_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 新车采购价格 失败');
                                }
                            }
                        }


                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '二手车采购价格') {
                                $ksa->total_amount = $total_amount_er_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细  二手车采购价格 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '购置税') {
                                $ksa->total_amount = $total_amount_gou_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 购置税 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '采购返利') {
                                $ksa->total_amount = $total_amount_cai_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 采购返利 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '交强险') {
                                $ksa->total_amount = $total_amount_jiao_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 交强险 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '上牌费用') {
                                $ksa->total_amount = $total_amount_shang_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 上牌费用 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '交强险') {
                                $ksa->total_amount = $total_amount_jiao_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 交强险 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '二手车过户费用') {
                                $ksa->total_amount = $total_amount_gouhu_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 二手车过户费用 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '转移待出口费用') {
                                $ksa->total_amount = $total_amount_zhuan_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 转移待出口费用 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '其他费用') {
                                $ksa->total_amount = $total_amount_qi_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 其他费用 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '退税') {
                                $ksa->total_amount = $total_amount_tui_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 退税 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '港杂费用') {
                                $ksa->total_amount = $total_amount_gang_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 港杂费用 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '国际运费') {
                                $ksa->total_amount = $total_amount_guonei_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 国际运费 失败');
                                }
                            }
                        }

                        foreach ($sales_order_amount_detail_zero as $ksa) {
                            if ($ksa->price_name == '国际运输保险费用') {
                                $ksa->total_amount = $total_amount_guowai_data['total_amount'];
                                $ksa->sales_order_sn = $order_sn;
                                unset($ksa->id);
                                $ksa = get_object_vars($ksa); // 对象转数组函数
                                $bill_details_id = WaOrdersSalesAmountDetail::created($ksa); // 创建订单详情
                                if (!$bill_details_id) {
                                    return IndexController::errored($bill_details_id, '添加销售订单账单明细 国际运输保险费用 失败');
                                }
                            }
                        }

                    }
                }

                \support\Db::commit();
                return IndexController::successed('', '订单更新成功');
            } catch (\Throwable $exception) {
                IndexController::logError('salesOrderList', $param, $adminId, $exception);
                \support\Db::rollBack();
                return IndexController::errored($exception, '订单更新失败');
            }
        }

    }
//


    public static function ordersOperateLog($data, $param)
    {
        if (array_key_exists('confirm_time', $param)) {
            if ($param['confirm_time']) {
                $data['confirm_time'] = $param['confirm_time'];
            }
        }
        $ordersOperateLog = WaOrdersOperateLog::created($data);
        if (!$ordersOperateLog) {
            return '销售订单日志操作失败';
        }

        return 'true';
    }

    public static function ordersStatusUp($order_sn, $status)
    {
        PublicCommentController::销售订单状态;
        $data = [
            'status' => intval($status),
            'updated_at' => dateTime(),
        ];
        $where = [];
        $where [] = ['order_sn', '=', $order_sn];
        $find = WaOrders::find($where);
        $find = json_decode($find);
        if (!$find) {
            return '查不到订单信息';
        }
//        if (intval($find->status) == $status) {
//            return '状态一致无需重复修改';
//        }
        $up = WaOrders::updated($data, $where);
        if (!$up) {
            return '状态修改失败';
        }

        return 'true';
    }

    public static function status($order_sn, &$status)
    {
        $find = WaOrders::find(['order_sn' => $order_sn]);
        $find = json_decode($find);
        if (!$find) {
            return '订单状态查询失败';
        }
        $status = $find->status;
        return 'true';
    }


    /**
     * 订单作废
     * @param Request $request
     * @return Response
     */
    public function orderCancellation(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 10; // 作废

        $describe = $adminId->nickname . '作废订单' . $param['order_sn'];
        \support\Db::beginTransaction();
        try {
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => '',
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payer_name' => '',
                'created_at' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }

            //修改审批状态为撤回审批
            WaSalesOrdersExamineApprove::updated(['sales_order_sn' => $param['order_sn']], ['status' => 3]);
            // 获取审批信息 用于添加日志记录
            $check = WaSalesOrdersExamineApprove::find(['sales_order_sn' => $param['order_sn']], $adminId);
            $check = json_decode($check);
            if ($check) {
                $approve_log_data = [
                    'sale_no' => $check->sale_no, // 销售订单编号
                    'check_id' => $check->id, // 审批id

                    'check_admin_type' => 0, // 1 主管审批  2 部门所有人中的任何一个  （撤回的时候可以是0）
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
                    'admin_name' => $adminId->nickname,
                    'status' => 3, //待审批 1审批通过 2 审批驳回 3 撤回 4  删除
                    'refuse_reason' => '审批被' . $adminId->nickname . '作废',
                    'sales_order_sn' => $param['order_sn'],
                ];

                $res = WaSalesOrdersExamineApproveFlow::create($approve_log_data);
                if (!$res) {
                    return IndexController::errored($res, '创建订单作废审批日志失败');
                }
            }


            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderCancellation', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }

    }

    /**
     * 更新-撤回审批 ()
     * 订单状态: 撤回草稿
     * @param Request $request
     * @return Response
     */
    public function orderWithdrawApprove(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }

        // 根据采购单编号获取订单信息
        $orders = WaOrders::find(['order_sn' => $param['order_sn']]);
        $orders = json_decode($orders);
        if (!$orders) {
            return IndexController::errored('', '获取销售单信息失败');
        }

        //销售订单状态
        PublicCommentController::销售订单状态;
        if ($status != 2) {
            return IndexController::errored('', '只有审批中的订单才能撤回审批');
        }
        $status = 0; // 0 草稿

        \support\Db::beginTransaction();
        try {
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $adminId->nickname . '撤回该订单' . $param['order_sn'] . '的审批修改状态为草稿',
                'remark' => '',
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,

                'created_at' => dateTime(),
            ];

            // 销售订单操作日志
            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }
            $status_up = OrderController::ordersStatusUp($param['order_sn'], $status);
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }
            //获取审批信息  审批中状态不为 3(撤回的数据) 删除的 不用考虑 列表查询时会过滤掉 用于添加日志记录   但是 一定要在状态更新前获取
//            $check = WaSalesOrdersExamineApprove::find([['sales_order_sn', '=', $param['order_sn']], ['status', '!=', 3]], $adminId);
            $check = WaSalesOrdersExamineApprove::find([['sales_order_sn', '=', $param['order_sn']], ['sale_no', '=', $orders->sale_no]], $adminId);
            $check = json_decode($check);
            if (!$check) {
                return IndexController::errored('', '无法获取该订单的审批数据');
            }
            //修改审批状态为撤回审批
            WaSalesOrdersExamineApprove::updated(['sales_order_sn' => $param['order_sn']], ['status' => 3, 'updated_at' => dateTime()]);

            $approve_log_data = [
                'sale_no' => $check->sale_no, // 销售订单编号
                'check_id' => $check->id, // 审批id
                'check_admin_type' => 0, // 1 主管审批  2 部门所有人中的任何一个  （撤回的时候可以是0）
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'status' => 3, //待审批 1审批通过 2 审批驳回 3 撤回 4  删除
                'refuse_reason' => '审批被' . $adminId->nickname . '撤销',
                'sales_order_sn' => $param['order_sn'],
            ];

            $res = WaSalesOrdersExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return IndexController::errored($res, '创建撤回审批日志失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderWithdrawApprove', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 退回草稿
     * @param Request $request
     * @return Response
     */
    public function orderReturnDraft(Request $request)
    {        //销售订单状态
        PublicCommentController::销售订单状态;
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
        if ($status){
            $status = intval($status);
        }
        // 旧 10,18
        // [2, 4, 12, 17, 18].includes(form.status)
        if(!in_array($status,[2, 4, 12, 17, 18])){
            return IndexController::errored('', '该接口只限 作废 和 审批驳回操作');
        }
        $status = 0; // 草稿

        $describe = $adminId->nickname . '退回草稿' . $param['order_sn'];
        \support\Db::beginTransaction();
        try {
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => '',
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'payer_name' => '',
                'created_at' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败');
            }

            $res = OrderController::ordersStatusUp($param['order_sn'], $status);
            if ($res != 'true') {
                return IndexController::errored($res, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed($res, '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('orderReturnDraft', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }


    /**
     * ...................................................车辆管理模块接口.................................................
     */


    /**
     * 更新-确认发货
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmShipment(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        // 订单状态  7待发货
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
//销售订单状态
        PublicCommentController::销售订单状态;
        if ($status != 7) {
            return IndexController::errored('', '待发货状态才能修改待收货');
        }
        $order_data = WaOrders::find(['order_sn' => $param['order_sn']]);
        $order_data = json_decode($order_data);

        //操作日志记录入参
        $voucher = json_encode($param['voucher']);
        $remark = $param['remark'];
        $confirm_time = dateTime(); // 确认时间
        $status = 8; //  待收货
        $describe = $adminId->nickname . '确认发货' . $param['order_sn'] . '状态修改为待收货';
        \support\Db::beginTransaction();
        try {
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
            ];
            if ($confirm_time) {
                $data['confirm_time'] = $confirm_time;
            }
            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }

            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('confirmShipment', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 更新-确认收货
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmReceipt(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        // 订单状态  8待收货
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
//销售订单状态
        PublicCommentController::销售订单状态;
        if ($status != 8) {
            return IndexController::errored('', '待收货状态才能修改已完成');
        }

        \support\Db::beginTransaction();
        try {
            //操作日志记录入参6lghjgvb
            $voucher = json_encode($param['voucher']);
            $remark = $param['remark'];
            $status = 9; //  交付提单（交车）
            $describe = $adminId->nickname . '确认收货' . $param['order_sn'] . '状态修改为已完成';
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('confirmReceipt', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 销售订单-报关确认
     * @param Request $request
     * @return Response
     */
    public function confirmDeclare(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
        //销售订单状态
        PublicCommentController::销售订单状态;
        if ($status != 13) {
            return IndexController::errored('', '待报关状态才能修改待发货');
        }
        $wpv_where = [];
        $wpv_where [] = ['sales_order_sn', '=', $param['order_sn']];
        $wpv_where [] = ['status', '<', 6];
        $wpv_find = WaPurchasedVehicles::find($wpv_where);
        $wpv_find = json_decode($wpv_find);
        if ($wpv_find) {
            return IndexController::errored($wpv_find, '该订单还有车辆未完成转移待出口');
        }


        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $voucher = json_encode($param['voucher']);
            $remark = $param['remark'];
            $status = 7; //  待发货
            $describe = $adminId->nickname . '报关确认' . $param['order_sn'] . '状态修改为待发货';
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('confirmDeclare', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }

    /**
     * 销售订单-交付提单(交车)
     *订单状态:
     * @param Request $request
     * @return Response
     */
    public function confirmDeliveryBill(Request $request)
    {
        //销售订单状态
        PublicCommentController::销售订单状态;
        // 订单状态  8待收货
        //        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 查看订单状态
        $status = 0;
        $status_check = OrderController::status($param['order_sn'],$status);
        if ($status_check != 'true'){
            return IndexController::errored('',$status_check);
        }
        //销售订单状态
        PublicCommentController::销售订单状态;
        if ($status != 15) {
            return IndexController::errored('', '交付提单状态才能修改已完成');
        }

        \support\Db::beginTransaction();
        try {
            //操作日志记录入参
            $voucher = json_encode($param['voucher']);
            $remark = $param['remark'];
            $status = 9; //  已完成
            $describe = $adminId->nickname . '交付提单(交车)' . $param['order_sn'] . '状态修改为已完成';
            // 销售订单操作日志
            $data = [
                'order_sn_parent' => $param['order_sn'],
                'status' => $status,
                'describe' => $describe,
                'remark' => $remark,
                'reason' => '',
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'voucher' => $voucher,
                'payer_name' => '',
                'created_at' => dateTime(),
                'confirm_time' => dateTime(),
            ];

            $order_log = OrderController::ordersOperateLog($data, $param);
            if ($order_log != 'true') {
                return IndexController::errored($order_log, '日志添加失败失败');
            }

            $status_up = OrderController::ordersStatusUp($param['order_sn'], intval($status));
            if ($status_up != 'true') {
                return IndexController::errored($status_up, '状态更新失败');
            }
            \support\Db::commit();
            return IndexController::successed('', '状态已更新');
        } catch (\Throwable $exception) {
            IndexController::logError('confirmDeliveryBill', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '状态更新失败');
        }
    }
//2
}